import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { User } from 'src/user/entities/user.entity'
import { Repository } from 'typeorm'
import { UpdateTodolistDto } from './dto/update-todolist.dto'
import { Todolist } from './entities/todolist.entity'

@Injectable()
export class TodolistService {
  constructor(
    @InjectRepository(Todolist) private readonly todolist: Repository<Todolist>,
    @InjectRepository(User) private readonly user: Repository<User>
  ) {}

  // 新增待办
  async create(body: any, req) {
    const userId = req.session.user_id
    // 用户对应的待办
    const user_data = await this.user.findOne({ relations: ['todolist'], where: { _id: userId } })

    const todolist = new Todolist()
    todolist.title = body.title

    await this.todolist.save(todolist)

    const user_todolist = user_data.todolist

    user_data.todolist = [...user_todolist, todolist]

    await this.user.save(user_data)

    return '新增成功'
  }

  // 查找所有的待办列表
  async findAll(req) {
    const userId = req.session.user_id

    const user_data = await this.user.findOne({ relations: ['todolist'], where: { _id: userId } })

    // 前端的List要指定一个id
    const handle_todolist = user_data.todolist.map(item => {
      return {
        ...item,
        id: item._id
      }
    })

    return handle_todolist
  }

  findOne(id: number) {
    return `This action returns a #${id} todolist`
  }

  // 是否完成待办
  async update(id: number, updateTodolistDto: UpdateTodolistDto) {
    await this.todolist.update(id, updateTodolistDto)
    const todolist_data = await this.todolist.findOne({ where: { _id: id } })

    return todolist_data
  }

  // 删除待办
  async remove(id: number) {
    await this.todolist.delete(id)
    return `删除笔记成功`
  }
}
